package com.pubinfo.passbook.data.controller.forward;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.pubinfo.passbook.common.entity.TPassbook;
import com.pubinfo.passbook.common.mapper.TSourcePassbookMapper;
import com.pubinfo.passbook.common.mapper.TSubsidiaryPrivateKeyMapper;
import com.pubinfo.passbook.common.model.bo.SubsidiaryInfo;
import com.pubinfo.passbook.common.model.bo.valueAddedTax.OutParamItem;
import com.pubinfo.passbook.common.model.dto.financial.CancelLockedRecord;
import com.pubinfo.passbook.common.model.dto.financial.InvoiceResult;
import com.pubinfo.passbook.common.model.dto.financial.Result;
import com.pubinfo.passbook.common.model.vo.base.JsonResult;
import com.pubinfo.passbook.common.service.master.TPassbookService;
import com.pubinfo.passbook.common.service.master.TWiteoffInstanceService;
import com.pubinfo.passbook.common.service.request.financial.RequestFinancialServer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "passbook")
@Api(tags = "票据管理")
@Slf4j
public class TPassbookController {
  @Autowired
  TPassbookService passbookService;
  @Autowired
  TSourcePassbookMapper passbookMapper;
  @Autowired
  private TSubsidiaryPrivateKeyMapper keyMapper;
  @Autowired
  RequestFinancialServer financialServer;
  @Autowired
  TWiteoffInstanceService tWiteoffInstanceService;
  
  @GetMapping("details/{id}")
  @ApiOperation(value = "查询详情")
  public JsonResult<InvoiceResult<Result>> details(@PathVariable("id") String eInvoiceId) throws IOException, UnirestException {
    return JsonResult.success(financialServer.detailList(eInvoiceId));
  }
  
  @PostMapping("detailsBatch")
  @ApiOperation(value = "批量查询详情")
  public InvoiceResult<Result> details(@RequestBody String[] eInvoiceIds) throws IOException, UnirestException {
    List<String> eInvoiceIdList = CollectionUtils.arrayToList(eInvoiceIds);
    if (financialServer.checkId(eInvoiceIdList)) {
      SubsidiaryInfo subsidiaryInfos = keyMapper.listFinSubsidiaryInfoByEinvoiceId(eInvoiceIds[0]);
      return financialServer.detailList(eInvoiceIdList, subsidiaryInfos);
    }
    return new InvoiceResult<Result>();
  }
  
  @PostMapping("detailsByInfo")
  @ApiOperation(value = "根据票据号查询详情")
  public InvoiceResult<Result> detailsByInfo(String eInvoiceId, String nsrsbh, Integer pdfType) {
    List<String> eInvoiceIdList = new ArrayList<>();
    eInvoiceIdList.add(eInvoiceId);
    List<SubsidiaryInfo> subsidiaryInfos = keyMapper.listFinAllSubsidiaryInfo(nsrsbh);
    return financialServer.detailList(eInvoiceIdList, subsidiaryInfos.get(0), pdfType);
  }
  
  @PostMapping("cancelLockedList")
  @ApiOperation(value = "批量解锁票据")
  public InvoiceResult<Object> cancelLockedList(@RequestBody String[] eInvoiceIds) {
    List<CancelLockedRecord> cancelLockedRecords = CancelLockedRecord.toList(eInvoiceIds);
    InvoiceResult<Object> invoiceResult = financialServer.cancelLockedList(cancelLockedRecords, "取消");
    if (invoiceResult.getSuccess()) {
      UpdateWrapper<TPassbook> updateWrapper = new UpdateWrapper<>();
      updateWrapper.in("e_invoice_id", CollectionUtils.arrayToList(eInvoiceIds));
      updateWrapper.set("is_locked", "N");
      passbookService.update(updateWrapper);
    }
    
    return invoiceResult;
  }

  @PostMapping("cancelClaimFeed")
  @ApiOperation(value = "撤销数据")
  public void cancelClaimFeed(@RequestBody OutParamItem outParamItem) {
    tWiteoffInstanceService.cancelClaimFeed(outParamItem);
  }
  
  @PostMapping("claimFeedback")
  @ApiOperation(value = "回传数据")
  public void claimFeedback(@RequestBody OutParamItem outParamItem) {
    tWiteoffInstanceService.claimFeedback(outParamItem);
  }
  
  @PutMapping("repair")
  @ApiOperation("修复数据")
  public JsonResult<Boolean> repair(@RequestBody final String[] eInvoiceIds) {
    QueryWrapper<TPassbook> queryWrapper = new QueryWrapper<>();
    queryWrapper.in("e_invoice_id", CollectionUtils.arrayToList(eInvoiceIds));
    //按公司分组，查询详情后设置数据
    List<TPassbook> passbookList = passbookService.list(queryWrapper);
    List<TPassbook> newPassbook = new ArrayList<>();
    if (!CollectionUtils.isEmpty(passbookList)) {
      Map<String, List<TPassbook>> nsrsbhMap = passbookList.stream().collect(Collectors.groupingBy(TPassbook::getNsrsbh));
      for (Map.Entry<String, List<TPassbook>> entry : nsrsbhMap.entrySet()) {
        String nsrsbh = entry.getKey();
        List<TPassbook> passbooks = entry.getValue();
        List<SubsidiaryInfo> subsidiaryInfos = keyMapper.listFinAllSubsidiaryInfo(nsrsbh);
        newPassbook.addAll(financialServer.setJson(passbooks, subsidiaryInfos.get(0)));
      }
    }
    return JsonResult.success(this.passbookService.updateBatchById(newPassbook));
  }
//
//  @PostMapping("downLoadPDF")
//  @ApiOperation(value = "根据id下载PDF")
//  public void downLoadPDF() throws IOException, UnirestException {
//    passbookService.downLoadPDF();
//  }
//
}
